package org.tanjor.common.shardingjdbc.shardrule.database;

import java.util.Collection;
import java.util.LinkedHashSet;

import org.tanjor.common.shardingjdbc.shardrule.ShardingUtil;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.SingleKeyDatabaseShardingAlgorithm;
import com.google.common.collect.Range;

public class ThreeDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<String> {
	@Override
	public String doEqualSharding(Collection<String> datasourceNames, ShardingValue<String> shardingValue) {
		// TODO Auto-generated method stub
		String value = shardingValue.getValue() + "";
		Integer num = ShardingUtil.idConvertInt(value);
		for (String each : datasourceNames) {			
			if (each.endsWith(num % 3 + "")) {
				return each;
			}
		}
		throw new IllegalArgumentException();
	}

	@Override
	public Collection<String> doInSharding(Collection<String> datasourceNames, ShardingValue<String> shardingValue) {
		// TODO Auto-generated method stub
		Collection<String> result = new LinkedHashSet<>(datasourceNames.size());
		for(int i=0;i<shardingValue.getValues().size();i++){
			String value = shardingValue.getValues().toArray()[i]+"";
			Integer num = ShardingUtil.idConvertInt(value);
			for (String datasourceName : datasourceNames) {
				if (datasourceName.endsWith(num % 3 + "")) {
					result.add(datasourceName);
				}
			}
		}
		return result;
	}

	@Override
	public Collection<String> doBetweenSharding(Collection<String> datasourceNames, ShardingValue<String> shardingValue) {
		// TODO Auto-generated method stub
		Collection<String> result = new LinkedHashSet<>(datasourceNames.size());
		Range<String> range = (Range<String>) shardingValue.getValueRange();
		for (Long i = Long.valueOf(range.lowerEndpoint()); i <= Long.valueOf(range.upperEndpoint()); i++) {
			for (String each : datasourceNames) {
				if (each.endsWith(i % 3 + "")) {
					result.add(each);
				}
			}
		}
		return result;
	}
}
